package com.live.task;

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveFavor extends AsyncTask<Bundle, Integer, String> {

	private Context context = null;

	private String matchId = null;

	private String teamName = null;

	private String homeTeam = null;

	private String visitTeam = null;

	private TextView homeFavor = null;

	private TextView visitFavor = null;

	private List<Map<String, Object>> favorDate;

	public LiveFavor(Context context, String teamName, TextView homeFavor, TextView visitFavor) {
		this.context = context;
		this.teamName = teamName;
		this.homeFavor = homeFavor;
		this.visitFavor = visitFavor;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("Comment", "onPreExecute()  " + Thread.currentThread().getId());
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。
	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("Comment", "doInBackground... " + Thread.currentThread().getId());

		matchId = params[0].getString("matchId");
		homeTeam = params[0].getString("homeTeamName");
		visitTeam = params[0].getString("visitTeamName");

		String url = Constant.SITE_URL + "live_team_favor.php?locale=" + LiveTools.getLocaleLanguage() + "&";
		if (teamName != null) {
			teamName = URLEncoder.encode(teamName);
		}
		url += "teamName=" + teamName + "&matchId=" + matchId;

		// 取得本机MAC地址
		String mac = LiveTools.getLocalMacAddress(context);
		if (mac == null) {
			mac = "android%20AVD";
		}
		// 此URL记录观看比赛者
		SharedPreferences store = context.getSharedPreferences(Constant.PREFS_NAME, 0);
		url += "&id=" + store.getString("id", null) + "&mac=" + mac;

		favorDate = setMatchFavor(url);

		publishProgress();
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());
		if (favorDate.size() > 0) {
			if (teamName != null) {
				// Toast.makeText(context, "投票成功！", Toast.LENGTH_LONG).show();
			}
			for (int i = 0; i < favorDate.size(); i++) {
				Map<String, Object> favor = favorDate.get(i);
				if (homeTeam.equals((String) favor.get("teamName"))) {
					homeFavor.setText((String) favor.get("count"));
				}
				if (visitTeam.equals((String) favor.get("teamName"))) {
					visitFavor.setText((String) favor.get("count"));
				}
			}
		} else {
			if (teamName != null) {
				Toast.makeText(context, "投票失败！", Toast.LENGTH_LONG).show();
			}
		}
	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		// tv.setText(result);
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
	}

	private List<Map<String, Object>> setMatchFavor(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							JSONArray favorList = new JSONObject(out).getJSONArray("results");
							for (int i = 0; i < favorList.length(); i++) {
								Map<String, Object> favor = new HashMap<String, Object>();
								favor.put("teamName", (String) favorList.getJSONObject(i).get("teamName"));
								favor.put("count", (String) favorList.getJSONObject(i).get("count"));
								data.add(favor);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

}